// pages/checkin/checkin.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    records: [
      {
        id: 1,
        image: "/images/checkin1.jpg",
        time: "2024-03-20 14:30",
        description: "参观了青铜器展区"
      }
    ],
    badges: [
      {
        id: 1,
        name: "初访",
        image: "/images/badge1.png",
        lockedImage: "/images/badge1_locked.png",
        unlocked: true
      },
      {
        id: 2,
        name: "收藏",
        image: "/images/badge2.png",
        lockedImage: "/images/badge2_locked.png",
        unlocked: false
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    // 检查相机权限
    wx.authorize({
      scope: 'scope.camera',
      success: () => {
        console.log('相机授权成功')
      },
      fail: () => {
        wx.showToast({
          title: '需要相机权限才能打卡',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  takePhoto: function () {
    const camera = wx.createCameraContext()
    camera.takePhoto({
      quality: 'high',
      success: (res) => {
        // 添加新的打卡记录
        const newRecord = {
          id: this.data.records.length + 1,
          image: res.tempImagePath,
          time: new Date().toLocaleString(),
          description: "新的打卡记录"
        }

        this.setData({
          records: [newRecord, ...this.data.records]
        })

        // 检查是否可以解锁新徽章
        this.checkBadges()
      },
      fail: () => {
        wx.showToast({
          title: '拍照失败',
          icon: 'none'
        })
      }
    })
  },

  checkBadges: function () {
    // 检查打卡次数，解锁对应徽章
    const checkinCount = this.data.records.length
    const badges = this.data.badges.map(badge => {
      if (badge.id === 2 && checkinCount >= 5) {
        badge.unlocked = true
      }
      return badge
    })

    this.setData({ badges })
  }
})